// pages/shoppingCart/shoppingCat.js
Page({
    /**
     * 页面的初始数据
     */
    data: {
      baseURL: 'http://43.139.97.111:8080',
      hasList: true, //购物车是否有数据
      totalMoney: 0, //总金额
      selectAllStatus: false, //是否全选
      userId: 22, //用户ID
      userInfo:{},
      totalCount: 0, //数量
      carts: [],
      booklist: [10],
      temp: '',
    },
  
    //设置文本框值
    bindIptCartNum: function (e) {
      const index = e.currentTarget.dataset.index;
      var num = e.detail.value;
      let carts = this.data.carts;
      carts[index].bookNumber = num;
      this.setData({
        carts: carts
      });
    },
  
    /* 点击减号 */
    bindMinus: function (e) {
      const index = e.currentTarget.dataset.index;
      let carts = this.data.carts;
      let num = carts[index].bookNumber;
      if (num <= 1) {
        return false;
      }
      num = num - 1;
      carts[index].bookNumber = num;
      this.setData({
        carts: carts
      });
      this.getTotalPrice();
      this.updateNumber(index);
    },
  
    /* 点击加号 */
    bindPlus: function (e) {
      const index = e.currentTarget.dataset.index;
      let carts = this.data.carts;
      let num = carts[index].bookNumber;
      num = num + 1;
      carts[index].bookNumber = num;
      this.setData({
        carts: carts
      });
      this.getTotalPrice();
      this.updateNumber(index);
    },
  
    //更新商品
    updateNumber:function(index){
      var _this = this
      console.log(index)
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.request({
        url: 'http://43.139.97.111:8080/cartItem/update',
        data: {
            bookId: _this.data.carts[index].bookId,
            bookNumber: _this.data.carts[index].bookNumber,
            cartItemId: _this.data.carts[index].cartItemId,
            userId: _this.data.carts[index].userId,
        },
        header: {
           'content-type': 'application/json' // 默认值
        },
        method: 'PUT',
        success: function (res) {
          console.log("res", res); 
          //_this.getCart()
          wx.hideLoading()
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    },
  
    //删除商品
    bindCartsDel(e) {
      const index = e.currentTarget.dataset.index;
      var _this = this;
      wx.showModal({
        title: '提示',
        content: '您确定要删除吗？',
        success: function (res) {
          if (res.confirm) {
            //请求删除购物车数据
            console.log(index)
            wx.showLoading({
              title: '加载中',
              mask: true
            })
            wx.request({
              url: 'http://43.139.97.111:8080/cartItem/update',
              data: {
                  bookId: _this.data.carts[index].bookId,
                  bookNumber: _this.data.carts[index].bookNumber,
                  cartItemId: _this.data.carts[index].cartItemId,
                  userId: _this.data.carts[index].userId,
                  deleteFlag:1,
                  cartItemStatus:0
              },
              header: {
                 'content-type': 'application/json' // 默认值
              },
              method: 'PUT',
              success: function (res) {
                console.log("res", res); 
                _this.getCart()
                wx.hideLoading()
              },
              fail: function (res) { },
              complete: function (res) { },
            })
          }
        }
      })
    },

    //绑定单选
    bindCheckbox: function (e) {
      var that = this;
      const idx = e.currentTarget.dataset.index;
      let carts = that.data.carts;
      // const isSelect1 = carts[idx].isSelect;
      // carts[idx].isSelect = !isSelect1;
      // that.setData({
      //   carts: carts,
      //   selectAllStatus: false
      // });
      if(carts[idx].cartItemStatus==0){
        that.updataSelect(idx,1)
      }else{
        that.updataSelect(idx,0)
      }
      that.getTotalPrice();
    },
  
    //绑定多选
    bindSelectAll: function (e) {
      var that = this;
      let selectedAllStatus = that.data.selectAllStatus;
      let carts = that.data.carts;

      selectedAllStatus = !selectedAllStatus;
      if(selectedAllStatus){
        for (var i = 0; i < carts.length; i++) {
          that.updataSelect(i,1)
        }
      }else{
        for (var i = 0; i < carts.length; i++) {
          that.updataSelect(i,0)
        }
      }
      that.setData({
        selectAllStatus: selectedAllStatus
      });
      that.getTotalPrice();
    },
    
    //更新选中状态
    updataSelect(index,status){
      var _this = this
      console.log(index)
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.request({
        url: 'http://43.139.97.111:8080/cartItem/update',
        data: {
            cartItemId: _this.data.carts[index].cartItemId,
            userId: _this.data.carts[index].userId,
            cartItemStatus:status
        },
        header: {
           'content-type': 'application/json' // 默认值
        },
        method: 'PUT',
        success: function (res) {
          console.log("res", res); 
          _this.getCart()
          _this.getTotalPrice()
          wx.hideLoading()
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    },
      //计算总价
      getTotalPrice() {
        let carts = this.data.carts; // 获取购物车列表
        let total = 0;
        let num = 0;
        for (let i = 0; i < carts.length; i++) { // 循环列表得到每个数据
          if (carts[i].cartItemStatus===1) { // 判断选中才会计算价格
            total += carts[i].bookNumber * carts[i].books.bookPrice; // 所有价格加起来
            num += carts[i].bookNumber;
          }
        }
        this.setData({ // 最后赋值到data中渲染到页面
          carts: carts,
          totalCount: num,
          totalMoney: total.toFixed(2)
        });
      },  
  
    //购物车结算
    bindjiesuan: function () {
      var that = this;
      let carts = that.data.carts;
      let selectItem = [];
      var j = 0
      for (var i = 0; i < carts.length; i++) {
        if (carts[i].cartItemStatus==1) {
          selectItem[j] = carts[i];
          j++;
        }
      }
      console.log(selectItem)
      if (selectItem.length <= 0) {
        wx.showToast({
          title: '未选择商品',
          icon: 'success',
          duration: 1000
        })
        return;
      }
      wx.setStorageSync('selectItem', selectItem); //存入缓存
      //转到结算页面
      wx.navigateTo({
        // url: '/pages/pay/pay?amount=' + that.data.totalMoney
        url: '/pages/pay/pay?paylist=' + JSON.stringify(selectItem)+'&totalMoney='+that.data.totalMoney
      });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      var _this = this;
      const userinfo = wx.getStorageSync("userInfo");
      this.setData({
        userInfo: userinfo
      });
      console.log(_this.data.userInfo.userId)
      if(_this.data.userInfo==''){
        wx.showToast({
          title: '请先登录',
          icon: 'success',
          duration: 2000
        })

      }else{
      _this.getCart()
      }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      var _this = this;
      const userinfo = wx.getStorageSync("userInfo");
      this.setData({
        userInfo: userinfo
      });
      console.log(_this.data.userInfo.userId)
      if(_this.data.userInfo==''){
        wx.showToast({
          title: '请先登录',
          icon: 'success',
          duration: 2000
        })
      }else{
      _this.getCart()
      _this.backData()
      }
    },

    //获取购物车数据
    getCart: function () {
      var uid = this.data.userInfo.userId;
      //网络请求获取购物车数据
      var _this = this;
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.request({
        url: 'http://43.139.97.111:8080/cartItem/queryByUserId2?userId=' + uid,
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          console.log(res.data);
          if (res.statusCode == 200&&res.data.data!='') {
            _this.setData({
              carts: res.data.data,
              hasList: true,
            })
          }else{
            _this.setData({
              hasList: false,
            })
          }
          // _this.getBook()
          _this.getTotalPrice()
          wx.hideLoading()
        }
      })
    },
  
    //加载书本数据
    getBook: function () {
      var _this = this
      console.log(_this.data.carts);
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      for (let i = 0; i < _this.data.carts.length; i++) {
        console.log(_this.data.carts[i].bookId)
        wx.request({
          url: 'http://43.139.97.111:8080/books/queryById?id=' + _this.data.carts[i].bookId,
          header: {
            'content-type': 'application/json' // 默认值
          },
          success(res) {
            console.log(res.data);
            if (res.statusCode == 200) {
              _this.setData({
                temp: res.data.data,
              })
              _this.data.booklist[i] = _this.data.temp
              _this.data.carts[i].bookAuthor = _this.data.temp.bookAuthor
              _this.data.carts[i].bookName = _this.data.temp.bookName
              _this.data.carts[i].bookPrice = _this.data.temp.bookPrice
              _this.data.carts[i].bookCover = _this.data.temp.bookCover
            }
          }
        })
      }
      setTimeout(()=>{
        _this.setData({
          carts:_this.data.carts
        })
      },400)
      wx.hideLoading()
    },

    
    //返回时处理数据
    backData(){
      var _this=this
      _this.setData({
        totalMoney:0,
        totalCount:0,
        selectAllStatus: false,
      })
    }
  })